package fmanganiello.tests.javatests.depinj.creditcard;

import java.util.Date;

import javax.naming.OperationNotSupportedException;

public class CreditCard {
	private String number;
	private double balance;
	private String owner;
	private Date expirationDate;

	public enum ChargeError {
		OK("OK"),
		EXPIRED_CARD("Expired credit card"),
		INSUFFICIENT_CREDIT("Insufficient credit card balance");
		
		ChargeError(String message) {}
	}
	
	public CreditCard(String number, double balance, String owner, Date expirationDate) {
		this.number = number;
		this.balance = balance;
		this.owner = owner;
		this.expirationDate = expirationDate;
	}

	public String getOwner() {
		return owner;
	}

	public String getNumber() {
		return number;
	}
	
	public ChargeError canChargeSum(double sum) {
		if (expirationDate.getTime() - new Date().getTime() < 0) {
			return ChargeError.EXPIRED_CARD;
		}
		
		if (balance - sum < 0) {
			return ChargeError.INSUFFICIENT_CREDIT;
		}
		
		return ChargeError.OK;
	}
	
	public synchronized void charge(double sum) throws OperationNotSupportedException {
		ChargeError chargeStatus = canChargeSum(sum);
		if (chargeStatus != ChargeError.OK) {
			throw new OperationNotSupportedException(chargeStatus.toString());
		}
		
		balance -= sum;
	}
}
